package service

import (
	"fmt"
	"go.uber.org/zap"
	"iot-base/common/cache"
	"iot-base/common/ctrltype"
	"iot-base/common/logger"
	"iot-base/common/notify"
	"regexp"
	"strconv"
	"strings"
	"time"

	"errors"
)

// 动态校准仪.
type Calo struct {
}

type CaloLogic struct {
}

func NewCaloLogic() *CaloLogic {
	return &CaloLogic{}
}

func (this *CaloLogic) Calo(id string, thing *cache.ThingInfo, v interface{}, round int64) (interface{}, error) {
	//ip := thing.GetThingParam("ip", "")
	//port := thing.GetThingParam("port", "")
	//calochr, err := SynHub.SendStrData(ip+":"+port, "calochr$")
	b, err := RequestData(thing, false, []byte("calochr$"))
	if err != nil {
		logger.Log.Error("Calo service.SynHub.SendStrData err:", zap.Error(err))
		return nil, err
	}
	calochr := string(b)
	if strings.Contains(calochr, "error") {
		logger.Log.Error("Calo service.SynHub.SendStrData err:" + calochr)
		return nil, err
	}
	logger.Log.Info("calochr$ " + calochr)
	fmt.Println("calochr$ info:=", calochr, err)
	caloArr := strings.Split(calochr, "=")
	var status float64 = 1
	switch caloArr[0][0:1] {
	case "*":
		status = 2
	case "#": //  $
		status = 3
	}
	reg := regexp.MustCompile("[\\d]+\\.[\\d]+")
	data := reg.Find([]byte(caloArr[1]))
	now := time.Now().Unix()
	o3, _ := strconv.ParseFloat(string(data), 64)
	notify.RawData(thing.Thing.UID, "o3", "", 0, o3, now, now)
	notify.RawData(thing.Thing.UID, "status", "", 0, status, now, now)
	notify.RawData(thing.Thing.UID, "ValueStatus", "", 0, fmt.Sprintf("%s%v", caloArr[0][0:1], o3), now, now)
	//0.0,0.0,2649.0,97.4,0.0,33.9,30.2,50.0,314.5,47.9,0.1,-0.5,0.3,0.0,-0.1,4003.6,602.4$
	// 获取状态.
	//calotwc, err := SynHub.SendStrData(ip+":"+port, "calotwc$")
	b, err = RequestData(thing, false, []byte("calotwc$"))
	calotwc := string(b)
	if err != nil {
		logger.Log.Error("calo service.SynHub.SendStrData err:", zap.Error(err))
		return nil, err
	}
	logger.Log.Info("calotwc$" + calotwc)
	if strings.Contains(calotwc, "error") {
		logger.Log.Error("So2 so2twc$ service.SynHub.SendStrData err:" + calotwc)
		return nil, err
	}
	calotwc = calotwc[:len(calotwc)-1]
	calotwcArr := strings.Split(calotwc, ",")
	pmt_v, _ := strconv.ParseFloat(calotwcArr[1], 64)
	notify.RawData(thing.Thing.UID, "pmt_v", "", 0, pmt_v, now, now)

	canbi_v, _ := strconv.ParseFloat(calotwcArr[2], 64)
	notify.RawData(thing.Thing.UID, "canbi_v", "", 0, canbi_v, now, now)

	power, _ := strconv.ParseFloat(calotwcArr[3], 64)
	notify.RawData(thing.Thing.UID, "power", "", 0, power, now, now)

	press, _ := strconv.ParseFloat(calotwcArr[4], 64)
	notify.RawData(thing.Thing.UID, "press", "", 0, press, now, now)

	flow, _ := strconv.ParseFloat(calotwcArr[5], 64)
	notify.RawData(thing.Thing.UID, "flow", "", 0, flow, now, now)

	temp, _ := strconv.ParseFloat(calotwcArr[6], 64)
	notify.RawData(thing.Thing.UID, "temp", "", 0, temp, now, now)

	boxtemp, _ := strconv.ParseFloat(calotwcArr[7], 64)
	notify.RawData(thing.Thing.UID, "boxtemp", "", 0, boxtemp, now, now)

	uvtemp, _ := strconv.ParseFloat(calotwcArr[8], 64)
	notify.RawData(thing.Thing.UID, "uvtemp", "", 0, uvtemp, now, now)

	o3gentemp, _ := strconv.ParseFloat(calotwcArr[9], 64)
	notify.RawData(thing.Thing.UID, "o3gentemp", "", 0, o3gentemp, now, now)

	zpress, _ := strconv.ParseFloat(calotwcArr[10], 64)
	notify.RawData(thing.Thing.UID, "zpress", "", 0, zpress, now, now)

	cpress, _ := strconv.ParseFloat(calotwcArr[11], 64)
	notify.RawData(thing.Thing.UID, "cpress", "", 0, cpress, now, now)

	tpress, _ := strconv.ParseFloat(calotwcArr[12], 64)
	notify.RawData(thing.Thing.UID, "tpress", "", 0, tpress, now, now)

	zflow, _ := strconv.ParseFloat(calotwcArr[13], 64)
	notify.RawData(thing.Thing.UID, "zflow", "", 0, zflow, now, now)

	cflow, _ := strconv.ParseFloat(calotwcArr[14], 64)
	notify.RawData(thing.Thing.UID, "cflow", "", 0, cflow, now, now)

	csqd_v, _ := strconv.ParseFloat(calotwcArr[15], 64)
	notify.RawData(thing.Thing.UID, "csqd_v", "", 0, csqd_v, now, now)

	geqd_v, _ := strconv.ParseFloat(calotwcArr[16], 64)
	notify.RawData(thing.Thing.UID, "geqd_v", "", 0, geqd_v, now, now)
	return nil, nil
}

func (this *CaloLogic) CaloSv(pCmd *ctrltype.CtrlCmd, tingInfo *cache.ThingInfo) (map[string]interface{}, error) {
	//ip := tingInfo.GetThingParam("ip", "")
	//port := tingInfo.GetThingParam("port", "")
	var requestMap map[string]interface{}
	requestMap = make(map[string]interface{})
	switch pCmd.ID {
	case "calzero":
		flow, ok := pCmd.Params["flow"].(string)
		if !ok {
			logger.Log.Error("calzero err", zap.Any("zero", "flow is unexit"))
			return nil, errors.New("flow is unexit")
		}
		if len(flow) < 4 {
			for i := 0; i < 4-len(flow); i++ {
				flow = "0" + flow
			}
		}
		//readbuffer, err := SynHub.SendStrData(ip+":"+port, "calzero,"+flow+"$")
		b, err := RequestData(tingInfo, true, []byte("calzero,"+flow+"$"))
		readbuffer := string(b)
		if err != nil {
			logger.Log.Error("calzero read err", zap.Error(err))
			return nil, errors.New("read err:" + err.Error())
		}
		if readbuffer == "calzerook$" {
			requestMap["msg"] = "ok"
		} else {
			logger.Log.Error("calzero fail")
			requestMap["msg"] = "fail:" + readbuffer
			return nil, errors.New("fail:" + readbuffer)
		}
		return requestMap, nil
	case "calzend":
		//readbuffer, err := SynHub.SendStrData(ip+":"+port, "calzend$")
		b, err := RequestData(tingInfo, true, []byte("calzend$"))
		readbuffer := string(b)
		if err != nil {
			logger.Log.Error("calzend read err", zap.Error(err))
			return nil, errors.New("read err:" + err.Error())
		}
		if readbuffer == "calzendok$" {
			requestMap["msg"] = "ok"
		} else {
			logger.Log.Error("calzend fail")
			requestMap["msg"] = "fail:" + readbuffer
			return nil, errors.New("fail:" + readbuffer)
		}
		return requestMap, nil
	case "calspan":
		flow, ok := pCmd.Params["flow"].(string)
		if !ok {
			logger.Log.Error("calzend flow is unexit", zap.Error(errors.New("flow is err")))
			return nil, errors.New("flow is unexit")
		}
		if len(flow) < 4 {
			for i := 0; i < 4-len(flow); i++ {
				flow = "0" + flow
			}
		}
		tp, ok := pCmd.Params["type"].(string)
		if !ok {
			logger.Log.Error("calzend type is unexit", zap.Error(errors.New("type is err")))
			return nil, errors.New("type is unexit")
		}
		concentration, ok := pCmd.Params["concentration"].(string)
		if !ok {
			logger.Log.Error("calzend concentration is unexit", zap.Error(errors.New("concentration is err")))
			return nil, errors.New("concentration is unexit")
		}
		if len(concentration) < 3 {
			for i := 0; i < 3-len(concentration); i++ {
				concentration = "0" + concentration
			}
		}
		units, ok := pCmd.Params["units"].(string)
		if !ok {
			logger.Log.Error("calzend units is unexit", zap.Error(errors.New("units is err")))
			return nil, errors.New("units is unexit")
		}
		//readbuffer, err := SynHub.SendStrData(ip+":"+port, fmt.Sprintf("calspan,%s,%s,%s,%s$", tp, flow, concentration, units))
		b, err := RequestData(tingInfo, true, []byte(fmt.Sprintf("calspan,%s,%s,%s,%s$", tp, flow, concentration, units)))
		readbuffer := string(b)
		if err != nil {
			logger.Log.Error("calzend thingId", zap.Error(err))
			return nil, errors.New("read err:" + err.Error())
		}
		if readbuffer == "calspanok$" {
			requestMap["msg"] = "ok"
		} else {
			requestMap["msg"] = "fail:" + readbuffer + fmt.Sprintf("calspan,%s,%s,%s,%s$", tp, flow, concentration, units)
			return nil, errors.New("fail:" + readbuffer + fmt.Sprintf("calspan,%s,%s,%s,%s$", tp, flow, concentration, units))
		}
		return requestMap, nil
	case "calsend":
		//readbuffer, err := SynHub.SendStrData(ip+":"+port, "calsend$")
		b, err := RequestData(tingInfo, true, []byte("calsend$"))
		readbuffer := string(b)
		if err != nil {
			logger.Log.Error("calsend read err", zap.Error(err))
			return nil, errors.New("read err:" + err.Error())
		}
		if readbuffer == "calsendok$" {
			requestMap["msg"] = "ok"
		} else {
			logger.Log.Error("calsend fail")
			requestMap["msg"] = "fail:" + readbuffer
			return nil, errors.New("fail:" + readbuffer)
		}
		return requestMap, nil
	case "status":
		//readbuffer, err := SynHub.SendStrData(ip+":"+port, "calochr$")
		b, err := RequestData(tingInfo, true, []byte("calochr$"))
		readbuffer := string(b)
		if err != nil {
			return nil, errors.New("read err:" + err.Error())
		}
		if strings.Contains(readbuffer, "error") {
			logger.Log.Error("calo service.SynHub.SendStrData err:" + readbuffer)
			fmt.Println("calochr$", readbuffer)
			return nil, err
		}
		logger.Log.Info("calo calochr$ info:=" + readbuffer)
		fmt.Println("calochr$ info:=", readbuffer, err)
		if err != nil {
			logger.Log.Error("calo service.SynHub.SendStrData err:", zap.Error(err))
			return nil, err
		}
		switch readbuffer[:1] {
		case "*":
			requestMap["msg"] = "2"
		case "#":
			requestMap["msg"] = "3"
		default:
			requestMap["msg"] = "1"
		}
		return requestMap, nil
	case "value":
		//readbuffer, err := SynHub.SendStrData(ip+":"+port, "calochr$")
		b, err := RequestData(tingInfo, true, []byte("calochr$"))
		readbuffer := string(b)
		if err != nil {
			return nil, errors.New("read err:" + err.Error())
		}
		if strings.Contains(readbuffer, "error") {
			logger.Log.Error("calo service.SynHub.SendStrData err:" + readbuffer)
			fmt.Println("calochr$", readbuffer)
			return nil, err
		}
		logger.Log.Info("calo calochr$ info:=" + readbuffer)
		fmt.Println("calochr$ info:=", readbuffer, err)
		if err != nil {
			logger.Log.Error("calo service.SynHub.SendStrData err:", zap.Error(err))
			return nil, err
		}
		data := strings.Split(readbuffer, "=")
		if len(data) != 2 {
			return nil, errors.New("return data is err:" + readbuffer)
		}
		data[1] = strings.Replace(data[1], "$", "", -1)
		if data[1][0] == '*' || data[1][0] == '#' {
			requestMap["value"] = data[1][1:]
		} else {
			requestMap["value"] = data[1]
		}
		return requestMap, nil
	default:
		logger.Log.Error("calo no this service")
		return nil, errors.New("no service")
	}

}
